package com.feature.core.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.feature.core.webmvc.CustomErrorController;
import com.feature.core.webmvc.CustomFastJsonHttpMessageConverter;
import com.feature.core.webmvc.GlobalControllerAdviceHandle;
import com.feature.core.webmvc.MDCInteceptor;
import com.feature.core.webmvc.WebMvcProperties;
import com.feature.core.webmvc.WebMvcProperties.CROS;


@AutoConfiguration(before = ErrorMvcAutoConfiguration.class)
@ConditionalOnClass(WebMvcConfigurer.class)
@EnableConfigurationProperties(WebMvcProperties.class)
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	private WebMvcProperties webMvcProperties;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new MDCInteceptor());
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		CROS cros = webMvcProperties.getCros();
		if (cros.isEnabled()) {
			// 添加映射路径
			registry.addMapping(cros.getMapping()).allowedOrigins(cros.getAllowedOrigins()) // 允许哪些域的请求，星号代表允许所有
					.allowedMethods(cros.getAllowedMethods().split(",")) // 允许的方法
					.allowedHeaders(cros.getAllowedHeaders()) // 允许的头部设置
					.allowCredentials(cros.isAllowCredentials()) // 是否发送 Cookie
					.maxAge(cros.getMaxAge()); // 预检间隔时间
		}
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.add(0, new CustomFastJsonHttpMessageConverter());
	}

	@Bean
	public CustomErrorController customErrorController() {
		return new CustomErrorController();
	}
	@Bean
	public GlobalControllerAdviceHandle globalControllerAdviceHandle() {
		return new GlobalControllerAdviceHandle();
	}

	@Bean
	public HttpMessageConverters customHttpMessageConverters() {
		HttpMessageConverters converters = new HttpMessageConverters(true, List.of(new CustomFastJsonHttpMessageConverter()));
		return converters;
	}
}
